package com.css.zfzx.sjcj.modules.qhriskvisualshow.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.utils.*;
import com.css.zfzx.sjcj.modules.boundary.Point;
import com.css.zfzx.sjcj.modules.boundary.repository.BoundaryNativeRepository;
import com.css.zfzx.sjcj.modules.boundary.repository.entity.BoundaryEntity;
import com.css.zfzx.sjcj.modules.boundary.viewobjects.BoundaryQueryParams;
import com.css.zfzx.sjcj.modules.pchjdzb.service.PcHjDzbService;
import com.css.zfzx.sjcj.modules.qhmapfiles.repository.QhMapFilesImport;
import com.css.zfzx.sjcj.modules.qhmapfiles.repository.entity.QhMapFilesEntity;
import com.css.zfzx.sjcj.modules.qhmapfiles.service.QhMapFilesService;
import com.css.zfzx.sjcj.modules.qhmapfiles.viewobjects.QhMapFilesQueryParams;
import com.css.zfzx.sjcj.modules.qhriskvisualshow.repository.QhProbabilityEarthquakeDangerNativeRepository;
import com.css.zfzx.sjcj.modules.qhriskvisualshow.repository.QhProbabilityEarthquakeDangerRepository;
import com.css.zfzx.sjcj.modules.qhriskvisualshow.repository.entity.QhProbabilityEarthquakeDangerEntity;
import com.css.zfzx.sjcj.modules.qhriskvisualshow.repository.QhProbabilityEarthquakeDangerImport;
import com.css.zfzx.sjcj.modules.qhriskvisualshow.service.QhProbabilityEarthquakeDangerService;
import com.css.zfzx.sjcj.modules.qhriskvisualshow.viewobjects.QhProbabilityEarthquakeDangerQueryParams;
import com.css.zfzx.sjcj.modules.qhriskvisualshow.viewobjects.QhProbabilityEarthquakeDangerVo;
import org.apache.commons.lang.StringUtils;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.opengis.feature.simple.SimpleFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @author andy
 * @date 2021-01-26
 */
@Service
public class QhProbabilityEarthquakeDangerServiceImpl implements QhProbabilityEarthquakeDangerService {

    private static final Logger log = LoggerFactory.getLogger(QhProbabilityEarthquakeDangerServiceImpl.class);

	@Autowired
    private QhProbabilityEarthquakeDangerRepository qhProbabilityEarthquakeDangerRepository;
    @Autowired
    private QhProbabilityEarthquakeDangerNativeRepository qhProbabilityEarthquakeDangerNativeRepository;
    @Autowired
    private QhProbabilityEarthquakeDangerImport qhProbabilityEarthquakeDangerInitial;
    @Autowired
    private QhMapFilesImport qhMapFilesImport;//上传文件管理
    @Autowired
    private PcHjDzbService pcHjDzbService;

    @Override
    public JSONObject queryQhProbabilityEarthquakeDangers(QhProbabilityEarthquakeDangerQueryParams queryParams, int curPage, int pageSize) {
        Page<QhProbabilityEarthquakeDangerEntity> qhProbabilityEarthquakeDangerPage = this.qhProbabilityEarthquakeDangerNativeRepository.queryQhProbabilityEarthquakeDangers(queryParams, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(qhProbabilityEarthquakeDangerPage);
        return jsonObject;
    }

    @Override
    public JSONObject queryQhProbabilityEarthquakeDangersByFileName(QhProbabilityEarthquakeDangerQueryParams queryParams, int curPage, int pageSize, String sort, String order) {
        if (!PlatformObjectUtils.isEmpty(sort) && sort.length() > 0) {
            sort = CheckObjFields.propertyChange(sort);
        }
        Page<QhProbabilityEarthquakeDangerEntity> qhProbabilityEarthquakeDangerPage = this.qhProbabilityEarthquakeDangerNativeRepository.queryQhProbabilityEarthquakeDangersByFileNameJDBC(queryParams, curPage, pageSize, sort, order);
                JSONObject jsonObject = PlatformPageUtils.formatPageData(qhProbabilityEarthquakeDangerPage);
        return jsonObject;
    }

    @Override
    public QhProbabilityEarthquakeDangerEntity getQhProbabilityEarthquakeDangerById(String id) {
        QhProbabilityEarthquakeDangerEntity qhProbabilityEarthquakeDanger = this.qhProbabilityEarthquakeDangerRepository.findById(id).orElse(null);
         return qhProbabilityEarthquakeDanger;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QhProbabilityEarthquakeDangerEntity saveQhProbabilityEarthquakeDanger(QhProbabilityEarthquakeDangerEntity qhProbabilityEarthquakeDanger) {
        String uuid = UUIDGenerator.getUUID();
        qhProbabilityEarthquakeDanger.setUuid(uuid);
        qhProbabilityEarthquakeDanger.setCreateUser(PlatformSessionUtils.getUserId());
        qhProbabilityEarthquakeDanger.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        this.qhProbabilityEarthquakeDangerRepository.save(qhProbabilityEarthquakeDanger);
        return qhProbabilityEarthquakeDanger;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QhProbabilityEarthquakeDangerEntity updateQhProbabilityEarthquakeDanger(QhProbabilityEarthquakeDangerEntity qhProbabilityEarthquakeDanger) {
        qhProbabilityEarthquakeDanger.setUpdateUser(PlatformSessionUtils.getUserId());
        qhProbabilityEarthquakeDanger.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        String id = qhProbabilityEarthquakeDanger.getUuid();
        QhProbabilityEarthquakeDangerEntity one = qhProbabilityEarthquakeDangerRepository.findById(id).get();
        BeanUtil.copyPropertiesIgnoreNull(qhProbabilityEarthquakeDanger, one);
        this.qhProbabilityEarthquakeDangerRepository.save(one);
        return qhProbabilityEarthquakeDanger;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteQhProbabilityEarthquakeDangers(List<String> ids) {
        List<QhProbabilityEarthquakeDangerEntity> qhProbabilityEarthquakeDangerList = this.qhProbabilityEarthquakeDangerRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(qhProbabilityEarthquakeDangerList) && qhProbabilityEarthquakeDangerList.size() > 0) {
            for(QhProbabilityEarthquakeDangerEntity qhProbabilityEarthquakeDanger : qhProbabilityEarthquakeDangerList) {
                this.qhProbabilityEarthquakeDangerRepository.delete(qhProbabilityEarthquakeDanger);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteQhProbabilityEarthquakeDangersByFileName(List<String> fileNames, String province) {
        int idx = -1;
        for (int i = 0; i < fileNames.size(); i++) {
            QhProbabilityEarthquakeDangerQueryParams queryParams = new QhProbabilityEarthquakeDangerQueryParams();
            queryParams.setProvince(province);
            queryParams.setAffiliatedFileName(fileNames.get(i));
            System.out.println(new Date()+"----开始删除." + fileNames.get(i));
            List<String> uuidList = this.qhProbabilityEarthquakeDangerNativeRepository.listQhProbabilityEarthquakeDangersUuidsByJDBC(queryParams);
            if(!PlatformObjectUtils.isEmpty(uuidList) && uuidList.size() > 0) {
                System.out.println(new Date()+"----开始逻辑删除." + uuidList.size() + "条数据");
                //物理删
                //qhProbabilityEarthquakeDangerInitial.sqlBatchDeleteEntities(qhPEDList);
                //逻辑删
                idx = qhProbabilityEarthquakeDangerInitial.newSqlBatchLogicDeleteEntities(province,uuidList);
                System.out.println(new Date()+"----结束逻辑删除." + uuidList.size() + "条数据");
            }
            //查询上传文件表
            QhMapFilesQueryParams qhMapFilesQueryParams = new QhMapFilesQueryParams();
            qhMapFilesQueryParams.setProvince(province);
            qhMapFilesQueryParams.setAffiliatedFileName(fileNames.get(i));
            qhMapFilesQueryParams.setType("PED_");//上传类型（PED_,RLM_,RLMPolygon_,SCR_）
            qhMapFilesQueryParams.setIsDelete("0");//未删除
            List<QhMapFilesEntity> list = qhMapFilesImport.searchMapFiles(qhMapFilesQueryParams);
            if(!PlatformObjectUtils.isEmpty(list) && list.size() > 0) {
                //逻辑删--上传文件表
                qhMapFilesImport.sqlBatchLogicDeleteEntities(list);
            }
            System.out.println(new Date()+"----结束删除." + fileNames.get(i));
        }
        return idx;
    }

    @Override
    public JSONObject getQhProbabilityEarthquakeDangers(QhProbabilityEarthquakeDangerQueryParams queryParams) {
        List<QhProbabilityEarthquakeDangerEntity> qhPEDEntities = this.qhProbabilityEarthquakeDangerNativeRepository.listQhProbabilityEarthquakeDangers(queryParams);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", qhPEDEntities);
        return jsonObject;
    }

    @Override
    public JSONObject searchQhProbabilityEarthquakeDangers(QhProbabilityEarthquakeDangerQueryParams queryParams) {
        List<QhProbabilityEarthquakeDangerEntity> qhPEDEntities = this.qhProbabilityEarthquakeDangerNativeRepository.searchProbabilityEarthquakeDangersByJDBC(queryParams);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("zoom", queryParams.getZoom());
        jsonObject.put("data", qhPEDEntities);
        return jsonObject;
    }

    @Override
    public void saveOrUpdate(QhProbabilityEarthquakeDangerEntity scrEntity) {
        QhProbabilityEarthquakeDangerQueryParams queryParams = new QhProbabilityEarthquakeDangerQueryParams();
        queryParams.setA(String.valueOf(scrEntity.getA()));
        queryParams.setB(String.valueOf(scrEntity.getB()));
        queryParams.setProvince(scrEntity.getProvince());
        queryParams.setCity(scrEntity.getCity());
        queryParams.setArea(scrEntity.getArea());
        List<QhProbabilityEarthquakeDangerEntity> scrEntities = qhProbabilityEarthquakeDangerNativeRepository.listQhProbabilityEarthquakeDangers(queryParams);
        // 若查到数据为空，则新增
        if (CollectionUtils.isEmpty(scrEntities)) {
            this.saveQhProbabilityEarthquakeDanger(scrEntity);
        } else {
            if (scrEntities.size() == 1) {
                QhProbabilityEarthquakeDangerEntity sourceProvinceEntity = scrEntities.get(0);
                BeanUtil.copyPropertiesIgnoreNull(scrEntity, sourceProvinceEntity);
                this.updateQhProbabilityEarthquakeDanger(sourceProvinceEntity);
            } else {
                throw new RuntimeException("库中该数据最多一条，请管理员清理数据库冗余数据！");
            }
        }
    }

    @Override
    public String judgeFileParams(String[] datas) {
        String str = "";
        Set<String> set = new HashSet<String>(Arrays.asList(datas));
        if(!set.contains("A")){
            str += "A,";
        }
        if(!set.contains("B")){
            str += "B,";
        }
        if(!set.contains("C")){
            str += "C,";
        }
        if(!set.contains("D")){
            str += "D,";
        }
        if(!set.contains("E")){
            str += "E,";
        }
        if(!set.contains("F")){
            str += "F,";
        }
        if(!set.contains("F")){
            str += "F,";
        }
        if(!set.contains("G")){
            str += "G,";
        }
        if(!set.contains("H")){
            str += "H,";
        }
        if(!set.contains("I")){
            str += "I,";
        }
        if(!set.contains("J")){
            str += "J,";
        }
        if(!set.contains("L")){
            str += "L,";
        }
        if(!set.contains("M")){
            str += "M,";
        }
        if(!set.contains("N")){
            str += "N,";
        }
        if(!set.contains("O")){
            str += "O,";
        }
        if(!set.contains("P")){
            str += "P,";
        }
        if(!set.contains("Q")){
            str += "Q,";
        }
        return str;
    }

    private String judgeFieldParams(List<List<Object>> list) {
        String str = "";
        for (int i = 0; i < list.size(); i++) {
            List<Object> values = list.get(i);
            for (int j = 0; j < values.size(); j++) {
                if ("".equals(values.get(j))) {
                    str += "第 " + i + " 条数据第 " + j + " 个字段数据为空.<br/>";
                }
            }
        }
        return str;
    }

    //场地数据 大于等于 基岩数据
    private boolean checkPlaceIsGreaterBasement(List<List<Object>> list) {
        String place = "", basement = "";
        for (int i = 0; i < list.size(); i++) {
            List<Object> attributes = list.get(i);
            for (int j = 3; j < attributes.size() - 1; j++) {
                place = attributes.get(j).toString();
                basement = attributes.get(j + 1).toString();
                if (Float.parseFloat(place) < Float.parseFloat(basement)) return false;
                j++;
            }
        }
        return true;
    }

    @Override
    public int lookUpQhProbabilityEarthquakeDangers(QhProbabilityEarthquakeDangerQueryParams queryParams, boolean isNewTable) {
        int count = this.qhProbabilityEarthquakeDangerNativeRepository.lookUpQhProbabilityEarthquakeDangers(queryParams, isNewTable);
        return count;
    }

    private boolean geometryIsEqualsCoordinate(String wkt, String lon, String lat) {
        //POINT (119.302 35.23300000088943)
        String wktPart = "";
        if (wkt.toLowerCase().indexOf("multipoint") != -1) {
            wktPart = wkt.substring(wkt.indexOf("(") + 2, wkt.lastIndexOf(")") - 1);
        } else if (wkt.toLowerCase().indexOf("point") != -1) {
            wktPart = wkt.substring(wkt.indexOf("(") + 1, wkt.lastIndexOf(")"));
        }

        int det = 1 + 6;
        String[] array = wktPart.split(" ");
        String longitude = array[0], latitude = array[1];
        String newWktLongitudeStr = keepDecimalDigits(longitude, det), newWktLatitudeStr = keepDecimalDigits(latitude, det);
        String newLongitudeStr = keepDecimalDigits(lon, det), newLatitudeStr = keepDecimalDigits(lat, det);

        double newWktLongitude = Double.parseDouble(newWktLongitudeStr), newWktLatitude = Double.parseDouble(newWktLatitudeStr);
        double newLongitude = Double.parseDouble(newLongitudeStr), newLatitude = Double.parseDouble(newLatitudeStr);

        if (newWktLongitude == newLongitude && newWktLatitude == newLatitude) return true;
        if (geometryIsEqualsCoordinatePart(longitude, latitude, lon, lat, det)) return true;
        return false;
    }
    /*private String keepDecimalDigits(String floatStr, int det) {
        int index = floatStr.indexOf("."), len = floatStr.length();
        if (index == -1) return floatStr;
        String floatPart = floatStr.substring(index + 1, (len > (index + det)) ? (index + det) : len);
        String newFloatStr = floatStr.substring(0, index) + "." + floatPart;
        return newFloatStr;
    }*/
    private String keepDecimalDigits(String floatStr, int det) {
        int index = floatStr.indexOf("."), len = floatStr.length();
        if (index == -1) return floatStr;
        int temp=det+3;
        String tempfloatPart=floatStr.substring(index + 1, (len > (index + temp)) ? (index + temp) : len);
        String floatPart = floatStr.substring(index + 1, (len > (index + det)) ? (index + det) : len);
        if(tempfloatPart.length()>floatPart.length()&&tempfloatPart.startsWith(floatPart)&&tempfloatPart.endsWith("9")){
            int findex=0;
            String sindex="";
            for(int i=floatPart.length()-1;i>0;i--){
                String subStr = floatPart.substring(i, i+1);
                if(subStr.equals("9")){
                    continue;
                }
                findex=i;
                sindex=Integer.toString(Integer.parseInt(subStr)+1);
                break;
            }
            floatPart= floatPart.substring(0, findex)+ sindex;
        }
        String newFloatStr = floatStr.substring(0, index) + "." + floatPart;
        return newFloatStr;
    }
    private static boolean geometryIsEqualsCoordinatePart(String longitude, String latitude, String lon, String lat, int det) {
        String newWktLongitudeStr = keepDecimalDigits2(longitude, det), newWktLatitudeStr = keepDecimalDigits2(latitude, det);
        String newLongitudeStr = keepDecimalDigits2(lon, det), newLatitudeStr = keepDecimalDigits2(lat, det);

        double newWktLongitude = Double.parseDouble(newWktLongitudeStr), newWktLatitude = Double.parseDouble(newWktLatitudeStr);
        double newLongitude = Double.parseDouble(newLongitudeStr), newLatitude = Double.parseDouble(newLatitudeStr);

        if (newWktLongitude == newLongitude && newWktLatitude == newLatitude) return true;
        return false;
    }
    private static String keepDecimalDigits2(String floatStr, int det) {
        int index = floatStr.indexOf("."), len = floatStr.length();
        if (index == -1) return floatStr;
        int temp=det+3;
        String tempfloatPart=floatStr.substring(index + 1, (len > (index + temp)) ? (index + temp) : len);
        String floatPart = floatStr.substring(index + 1, (len > (index + det)) ? (index + det) : len);
        if(tempfloatPart.length()>floatPart.length()&&tempfloatPart.startsWith(floatPart)&&floatPart.endsWith("9")){
            int findex=0;
            String sindex="";
            for(int i=floatPart.length()-1;i>0;i--){
                String subStr = floatPart.substring(i, i+1);
                if(subStr.equals("9")){
                    continue;
                }
                findex=i;
                sindex=Integer.toString(Integer.parseInt(subStr)+1);
                break;
            }
            floatPart= floatPart.substring(0, findex)+ sindex;
        }

        String newFloatStr = floatStr.substring(0, index) + "." + floatPart;
        return newFloatStr;
    }


    @Autowired
    private BoundaryNativeRepository boundaryNativeRepository;
    private String checkPointIsInDistrict(String province, String city, String area, List<List<Object>> list) {
        BoundaryQueryParams queryParams = new BoundaryQueryParams();
        queryParams.setType("1");
        queryParams.setLevel("2");
        queryParams.setProvince(province);
        queryParams.setCity(city);
        queryParams.setArea(area);
        queryParams.setName(area);
        List<BoundaryEntity> boundaryEntities = this.boundaryNativeRepository.listBoundaries(queryParams);
        if (boundaryEntities.size() == 1) {
            BoundaryEntity boundaryEntity = boundaryEntities.get(0);
            String coordinate = boundaryEntity.getCoordinate();
            if (coordinate == null || "".equals(coordinate)) {
                return "NoDistrictBoundaryData";
            } else {
                coordinate = coordinate.substring(coordinate.indexOf("(((") + 3, coordinate.lastIndexOf(")))"));
                coordinate = coordinate.replace(")), ((", "|");
                coordinate = coordinate.replace("), (", "#");
                List<Point[]> boundaries = new ArrayList<>();
                String[] coordinates = StringUtils.split(coordinate, "|");
                for (int j = 0; j < coordinates.length; j++) {
                    String[] lonlats = StringUtils.split(coordinates[j],", ");
                    Point[] points = new Point[lonlats.length];
                    for (int i = 0;i < lonlats.length;i++) {
                        String[] lonlat = StringUtils.split(lonlats[i], " ");
                        Point point = new Point();
                        point.x = Double.parseDouble(lonlat[0]);
                        point.y = Double.parseDouble(lonlat[1]);
                        points[i] = point;
                    }
                    boundaries.add(points);
                }

                int flag = 0;
                Point PGAPoint = null;
                String longitude = "", latitude = "";
                for (int i = 0; i < list.size(); i++) {
                    List<Object> attributes = list.get(i);
                    longitude = attributes.get(1).toString();
                    latitude = attributes.get(2).toString();
                    PGAPoint = new com.css.zfzx.sjcj.modules.boundary.Point(Double.parseDouble(longitude), Double.parseDouble(latitude));
                    flag = 0;
                    for (int j = 0; j < boundaries.size(); j++) {
                        Point[] boundary = boundaries.get(j);
                        if (AreaBoundaryUtil.isPointInPolygon(PGAPoint, boundary)) {
                            flag++;
                            break;
                        }
                    }
                    if (flag == 0) return "false";
                }
            }
        } else if (boundaryEntities.size() == 0) {
            return "NoDistrictBoundaryData";
        } else {
            return "DistrictBoundaryDataRedundance";
        }
        return "true";
    }
    private String getErrorInfo (String info, String province, String city, String area) {
        if ("NoDistrictBoundaryData".equals(info)) return "不存在" + province + city + area + "边界数据, 入库失败!";
        if ("DistrictBoundaryDataRedundance".equals(info)) return province + city + area + "边界数据冗余, 入库失败!";
        if ("false".equals(info)) return "存在数据不在" + province + city + area + "边界范围内的数据, 入库失败!";
        return "错误信息未知!";
    }

    private boolean checkResolutionSixSecond(List<List<Object>> list) {

        Map<Double, List<Double>> lon2latitudes = new HashMap<>();
        Map<Double, List<Double>> lat2longitudes = new HashMap<>();

        double lon = 0, lat = 0;
        for (int i = 0; i < list.size(); i++) {
            List<Object> attributes = list.get(i);
            String A = attributes.get(1).toString();
            String B = attributes.get(2).toString();
            lon = Double.parseDouble(A);
            lat = Double.parseDouble(B);

            if (lon2latitudes.containsKey(lon)) {
                lon2latitudes.get(lon).add(lat);
            } else {
                List<Double> latitudes = new ArrayList<>();
                latitudes.add(lat);
                lon2latitudes.put(lon, latitudes);
            }

            if (lat2longitudes.containsKey(lat)) {
                lat2longitudes.get(lat).add(lon);
            } else {
                List<Double> longitudes = new ArrayList<>();
                longitudes.add(lon);
                lat2longitudes.put(lat, longitudes);
            }
        }
        if (isLessSixSecond(lon2latitudes) || isLessSixSecond(lat2longitudes)) return true;
        return false;
    }
    private boolean isLessSixSecond(Map<Double, List<Double>> map) {
        double thresh = 6.5;
        for(Map.Entry<Double, List<Double>> entity : map.entrySet()) {
            List<Double> entityValues = entity.getValue();
            Collections.sort(entityValues);
            for (int i = 0; i < entityValues.size() - 1; i++) {
                double value1 = entityValues.get(i), value2 = entityValues.get(i + 1);
                double det = Math.abs(value1 - value2);
                if (det >= 1) return false;
                det *= 60;
                if (det >= 1) return false;
                det *= 60;
                if (det < thresh) return true;
            }
        }
        return false;
    }

    //保存到上传文件管理表
    private void saveMapFiles(QhMapFilesEntity qhMapFilesEntity) throws Exception {
        List<QhMapFilesEntity> list = new ArrayList<QhMapFilesEntity>();
        list.add(qhMapFilesEntity);
        String affiliatedFileName = qhMapFilesEntity.getAffiliatedFileName();
        String province = qhMapFilesEntity.getProvince();
        String city = qhMapFilesEntity.getCity();
        String area = qhMapFilesEntity.getArea();
        //逻辑删除未保存的文件
        deleteMapFileByParams(affiliatedFileName, province, city, area);
        //保存
        qhMapFilesImport.sqlBatchSaveEntities(list);
    }

    //逻辑删除未保存的文件
    private void deleteMapFileByParams(String affiliatedFileName, String province, String city, String area) {
        //查询上传文件表
        QhMapFilesQueryParams qhMapFilesQueryParams = new QhMapFilesQueryParams();
        qhMapFilesQueryParams.setProvince(province);
        qhMapFilesQueryParams.setCity(city);
        qhMapFilesQueryParams.setArea(area);
        //qhMapFilesQueryParams.setAffiliatedFileName(affiliatedFileName);
        qhMapFilesQueryParams.setType("PED_");//上传类型（PED_,RLM_,RLMPolygon_,SCR_）
        //查询文件（未删除）
        List<QhMapFilesEntity> list = qhMapFilesImport.searchMapFilesUnSaved(qhMapFilesQueryParams);
        if(!PlatformObjectUtils.isEmpty(list) && list.size() > 0) {
            //逻辑删--上传文件表
            qhMapFilesImport.sqlBatchLogicDeleteEntities(list);
        }
    }

    //校验shp文件
    public String checkSHPFiles(String filePath, String province, String city, String area) {
        System.out.println(new Date()+"-------------------1.开始readSHPFile");
        System.out.println(new Date()+"-------------------2.开始校验");
        //获取省市县所在区域字符串
        String boundariesCoordinate = getDistrictBoundaryCoordinate(province, city, area);
        //读取shp文件并校验--type上传类型（PED_,RLM_,RLMPolygon_,SCR_）
        List<Object> list = VectorDataUtil.readSHPFileCheck(filePath, "UTF-8","PED_", boundariesCoordinate);
        String codeType = (String) list.get(0);//编码类型（0：UTF-8，1：GBK）
        int dataLength = (int) list.get(1);//数据长度
        String checkResult = (String) list.get(2);//校验结果
        //编码类型（0：UTF-8，1：GBK）
        if (codeType.equals("UTF-8")) {
            codeType = "0";
        }else{
            codeType = "1";
        }
        if(checkResult.equals("校验成功")){
            System.out.println(new Date()+"-------------------1.完成校验GeometryIsNotEqualsCoordinate");
            System.out.println(new Date()+"-------------------2.完成校验是否有乱码");
            System.out.println(new Date()+"-------------------3.完成校验字段空值");
            System.out.println(new Date()+"-------------------4.完成校验空间分辨率是否为6秒");
            System.out.println(new Date()+"-----------校验成功.");
        }else{
            System.out.println(new Date()+"-----------校验失败."+checkResult);
            return checkResult;
        }
        System.out.println(new Date()+"-----------3.结束校验");

        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length() - 4);
        // 返回的消息
        StringBuilder returnMsg = new StringBuilder();
        //上传文件信息
        QhMapFilesEntity qhMapFilesEntity = new QhMapFilesEntity();
        qhMapFilesEntity.setFilepath(filePath);
        qhMapFilesEntity.setProvince(province);
        qhMapFilesEntity.setCity(city);
        qhMapFilesEntity.setArea(area);
        qhMapFilesEntity.setAffiliatedFileName(fileName);
        qhMapFilesEntity.setIsSave("0");
        qhMapFilesEntity.setIsDelete("0");
        qhMapFilesEntity.setType("PED_");//类型
        qhMapFilesEntity.setPostfix("shp");
        qhMapFilesEntity.setQualityStatus("1");//上传省市级类型（0：省，1：市）
        qhMapFilesEntity.setCodeType(codeType);//编码类型（0：UTF-8，1：GBK）
        qhMapFilesEntity.setDataLength(dataLength);//数据长度
        try {
            System.out.println(new Date()+"-------------------4.开始保存");
            //保存到上传文件管理表
            this.saveMapFiles(qhMapFilesEntity);
            System.out.println(new Date()+"-------------------5.结束保存");
            returnMsg.append("等待导入" + dataLength + "条数据.请第二天查询上传内容.");
            return returnMsg.toString();
        } catch (RuntimeException e) {
            log.error(e.getMessage(), e);
            return "插入或更新数据出现错误: <br/>" + e.getMessage();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "数据导入失败, 服务器内部出现异常!";
        }
    }

    //保存--zyt
    @Override
    public String newImportShapeFile(String filePath, String province, String city, String area, String createUser,String codeType,int dataLength) {
        // 返回的消息
        StringBuilder returnMsg = new StringBuilder();
        try {
            System.out.println(new Date()+"-------------------1.开始保存");
            //保存--zyt
            int count = this.newSaveData(filePath,province,city,area, codeType, dataLength,createUser);
            if(count==dataLength){
                //保存一条记录：dataType(1:PGA,2等级图矢量点)
                pcHjDzbService.jdbcSave(province, city, area,"1");
                System.out.println(new Date()+"-------------------2.结束保存");
                returnMsg.append("成功导入" + count + "条数据.");
            }else{
                System.out.println(new Date()+"-------------------2.结束保存");
                returnMsg.append("导入出现异常，仅导入" + count + "条数据.");
            }
            return returnMsg.toString();
        } catch (RuntimeException e) {
            log.error(e.getMessage(), e);
            return "插入或更新数据出现错误: <br/>" + e.getMessage();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "数据导入失败, 服务器内部出现异常!";
        }
    }

    //保存--zyt
    private int newSaveData(String filePath, String province, String city, String area, String codeType, int dataLength, String createUser) {
        int count = qhProbabilityEarthquakeDangerInitial.newSqlBatchSaveEntities(filePath,province,city,area,codeType,dataLength,createUser);

        return count;
    }

    /*@Autowired
    private BoundaryNativeRepository boundaryNativeRepository;*/
    //获取省市县所在区域字符串
    public String getDistrictBoundaryCoordinate(String province, String city, String area){
        String coordinate = "";
        BoundaryQueryParams queryParams = new BoundaryQueryParams();
        queryParams.setType("1");//1: 行政区划 2: 普查区划
        if(PlatformObjectUtils.isEmpty(area)){//市
            queryParams.setLevel("1");//0: 省 1: 市 2: 县
            queryParams.setName(city);
        }else{//县
            queryParams.setLevel("2");//0: 省 1: 市 2: 县
            queryParams.setName(area);
        }
        queryParams.setProvince(province);
        queryParams.setCity(city);
        queryParams.setArea(area);
        //查询省市县所在区域边界列表
        List<BoundaryEntity> boundaryEntities = this.boundaryNativeRepository.newListBoundaries(queryParams);
        if (boundaryEntities.size() == 1) {
            BoundaryEntity boundaryEntity = boundaryEntities.get(0);
            coordinate = boundaryEntity.getCoordinate();

        } else if (boundaryEntities.size() == 0) {
            System.out.println("NoDistrictBoundaryData");
        } else {
            System.out.println("DistrictBoundaryDataRedundance");
        }
        return coordinate;
    }

    //校验GDB文件
    public String checkGDBFiles(String filePath, String province, String city, String area) {
        System.out.println(new Date()+"-------------------1.开始readGDBFile");
        System.out.println(new Date()+"-------------------2.开始校验");
        //获取省市县所在区域字符串
        String boundariesCoordinate = getDistrictBoundaryCoordinate(province, city, area);
        //读取GDB文件并校验--type上传类型（PED_,RLM_,RLMPolygon_,SCR_）
        List<Object> list = GdbDataUtil.readGDBFileCheck(filePath, "UTF-8","PED_", boundariesCoordinate);
        String codeType = (String) list.get(0);//编码类型（0：UTF-8，1：GBK）
        int dataLength = (int) list.get(1);//数据长度
        String checkResult = (String) list.get(2);//校验结果
        //编码类型（0：UTF-8，1：GBK）
        if (codeType.equals("UTF-8")) {
            codeType = "0";
        }else{
            codeType = "1";
        }
        if(checkResult.equals("校验成功")){
            System.out.println(new Date()+"-------------------1.完成校验GeometryIsNotEqualsCoordinate");
            System.out.println(new Date()+"-------------------2.完成校验是否有乱码");
            System.out.println(new Date()+"-------------------3.完成校验字段空值");
            System.out.println(new Date()+"-------------------4.完成校验空间分辨率是否为6秒");
            System.out.println(new Date()+"-----------校验成功.");
        }else{
            System.out.println(new Date()+"-----------校验失败."+checkResult);
            return checkResult;
        }
        System.out.println(new Date()+"-----------3.结束校验");

        //String fileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length() - 4);
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length());
        // 返回的消息
        StringBuilder returnMsg = new StringBuilder();
        //上传文件信息
        QhMapFilesEntity qhMapFilesEntity = new QhMapFilesEntity();
        qhMapFilesEntity.setFilepath(filePath);
        qhMapFilesEntity.setProvince(province);
        qhMapFilesEntity.setCity(city);
        qhMapFilesEntity.setArea(area);
        qhMapFilesEntity.setAffiliatedFileName(fileName);
        qhMapFilesEntity.setIsSave("0");
        qhMapFilesEntity.setIsDelete("0");
        qhMapFilesEntity.setType("PED_");//类型
        qhMapFilesEntity.setPostfix("gdb");
        qhMapFilesEntity.setQualityStatus("1");//上传省市级类型（0：省，1：市）
        qhMapFilesEntity.setCodeType(codeType);//编码类型（0：UTF-8，1：GBK）
        qhMapFilesEntity.setDataLength(dataLength);//数据长度
        try {
            System.out.println(new Date()+"-------------------4.开始保存");
            //保存到上传文件管理表
            this.saveMapFiles(qhMapFilesEntity);
            System.out.println(new Date()+"-------------------5.结束保存");
            returnMsg.append("等待导入" + dataLength + "条数据.请第二天查询上传内容.");
            return returnMsg.toString();
        } catch (RuntimeException e) {
            log.error(e.getMessage(), e);
            return "插入或更新数据出现错误: <br/>" + e.getMessage();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "数据导入失败, 服务器内部出现异常!";
        }
    }

    //保存GDB文件
    @Override
    public String newImportGDBFile(String filePath, String province, String city, String area, String createUser,String codeType,int dataLength) {
        // 返回的消息
        StringBuilder returnMsg = new StringBuilder();
        try {
            System.out.println(new Date()+"-------------------1.开始保存");
            //保存GDB文件
            int count = qhProbabilityEarthquakeDangerInitial.newSqlBatchSaveEntities_GDB(filePath,province,city,area,codeType,dataLength,createUser);
            if(count==dataLength){
                //保存一条记录：dataType(1:PGA,2等级图矢量点)
                pcHjDzbService.jdbcSave(province, city, area,"1");
                System.out.println(new Date()+"-------------------2.结束保存");
                returnMsg.append("成功导入" + count + "条数据.");
            }else{
                System.out.println(new Date()+"-------------------2.结束保存");
                returnMsg.append("导入出现异常，仅导入" + count + "条数据.");
            }
            return returnMsg.toString();
        } catch (RuntimeException e) {
            log.error(e.getMessage(), e);
            return "插入或更新数据出现错误: <br/>" + e.getMessage();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "数据导入失败, 服务器内部出现异常!";
        }
    }
}
